package com.atguigu.gmall.pay.paycontroller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.config.mq.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@Api(tags = "修改订单支付状态")
@RequestMapping("/api/payment")
@RestController
public class PaySuccessNotifyController {

    @Autowired
    AlipayProperties alipayProperties;
    @Autowired
    MqService mqService;

    //支付成功以后 支付宝会给我们发送请求，通知我们支付结果
    @PostMapping("/notify/success")
    public String paySuccessNotify (@RequestParam Map<String,String> params) throws AlipayApiException {

        log.info("收到支付宝的支付结果：{}", JSON.toJSONString(params));

        //验证签名 只能是支付宝给我们发的请求才可以
        boolean signVerifeld = AlipaySignature.rsaCheckV1(params,
                alipayProperties.getAlipay_public_key(), alipayProperties.getCharset(),
                alipayProperties.getSign_type());
        if (signVerifeld){
            log.info("验签通过，准备修改订单状态");
            // 修改订单状态，通过消息传递机制
            String trade_status = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)){//订单状态 == 支付宝 支付成功
                mqService.send(params,MqConst.ORDER_EVENT_EXCHANGE, MqConst.ORDER_PAYED_RK);
            }
        }

        //我们（商家）反馈给支付宝 返回 success，不然支付宝会在25小时内发送八次通知支付结果
        return "success";
    }
}
